package com.danikula.videocache.util;

import com.danikula.videocache.Preconditions;

import static com.danikula.videocache.Preconditions.checkNotNull;

import ohos.miscservices.pasteboard.PasteData;
import ohos.utils.net.Uri;

import java.io.Closeable;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Optional;
import java.util.regex.Pattern;
import java.io.UnsupportedEncodingException;

/**
 * Just simple utils.
 *
 * @author Alexey Danilov .
 */
public class ProxyCacheUtils {
    private static final String TAG = "ProxyCacheUtils";
    /**
     * 默认的读取长度
     */
    public static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
    static final int MAX_ARRAY_PREVIEW = 16;

    /**
     * 获取文件类型
     *
     * @param url 文件URL
     * @return 文件类型
     */
    public static String getSupposablyMime(String url) {
        Uri uri = Uri.parse(url);
        PasteData mimes = PasteData.creatUriData(uri);
        String extension = getExtension(url);
        boolean isEmpty = extension == null || extension.length() == 0;
        return isEmpty ? "" : mimes.getPrimaryMimeType();
    }

    static String getExtension(String url) {
        if (!(url == null || url.length() == 0)) {
            int fragment = url.lastIndexOf('#');
            if (fragment > 0) {
                url = url.substring(0, fragment);
            }

            int query = url.lastIndexOf('?');
            if (query > 0) {
                url = url.substring(0, query);
            }

            int filenamePos = url.lastIndexOf('/');
            String filename =
                    filenamePos >= 0 ? url.substring(filenamePos + 1) : url;

            /**
             * if the filename contains special characters,
             * we don't consider it valid for our matching purposes:
             */
            if (!filename.isEmpty() &&
                    Pattern.matches("[a-zA-Z_0-9\\.\\-\\(\\)\\%]+", filename)) {
                int dotPos = filename.lastIndexOf('.');
                if (dotPos >= 0) {
                    return filename.substring(dotPos + 1);
                }
            }
        }

        return "";
    }

    /**
     * 对输入输出数据做判空检测
     *
     * @param buffer 输入输出数据
     * @param offset 输入输出起止点
     * @param length 输入输出长度
     */
    public static void assertBuffer(byte[] buffer, long offset, int length) {
        checkNotNull(buffer, "Buffer must be not null!");
        Preconditions.checkArgument(offset >= 0, "Data offset must be positive!");
        Preconditions.checkArgument(length >= 0 && length <= buffer.length, "Length must be in range [0..buffer" +
                ".length]");
    }

    static String preview(byte[] data, int length) {
        int previewLength = Math.min(MAX_ARRAY_PREVIEW, Math.max(length, 0));
        byte[] dataRange = Arrays.copyOfRange(data, 0, previewLength);
        String preview = Arrays.toString(dataRange);
        if (previewLength < length) {
            preview = preview.substring(0, preview.length() - 1) + ", ...]";
        }
        return preview;
    }

    /**
     * 加密URL
     *
     * @param url 未加密的视频URL
     * @return 加密之后的视频URL
     * @throws UnsupportedEncodingException 不支持的加解密错误
     */
    public static String encode(String url) throws UnsupportedEncodingException {
        try {
            return URLEncoder.encode(url, "utf-8");
        } catch (IOException e) {
            throw new UnsupportedEncodingException("Error encoding url" + e.toString());
        }
    }

    /**
     * 解密
     *
     * @param url 加密之后的视频URL
     * @return 解密之后的视频URL
     * @throws UnsupportedEncodingException 不支持的加解密错误
     */
    public static String decode(String url) throws UnsupportedEncodingException {
        try {
            return URLDecoder.decode(url, "utf-8");
        } catch (IOException e) {
            throw new UnsupportedEncodingException("Error decoding url" + e.toString());
        }
    }

    /**
     * 关闭输入流
     *
     * @param closeable 输入/出流
     */
    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                LogUtil.error(TAG, "Error closing resource" + e.toString());
            }
        }
    }

    /**
     * 通过对视频URL做MD5加密处理生成新的缓存文件的文件名
     *
     * @param string 视频URL
     * @return 缓存文件的文件名
     */
    public static String computeMD5(String string) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digestBytes = messageDigest.digest(string.getBytes(Charset.defaultCharset()));
            return bytesToHexString(digestBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (byte buffer : bytes) {
            sb.append(String.format("%02x", buffer));
        }
        return sb.toString();
    }
}
